package com.gohead.server.crawel.loop;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public abstract class LoopTasks<T extends LoopTask> implements Runnable {
    /**
     * task pool
     */
    private LinkedBlockingQueue<T> tasks;


    private Thread demaon = new Thread(this::run);
    /**
     * loop state
     */
    private boolean running = false;

    private int waiting = 300;

    private final static int DEFAULT_TASK_SIZE = 200;


    public LoopTasks(int size) {
        tasks = new LinkedBlockingQueue<>(size);
    }

    public LoopTasks() {
        this(DEFAULT_TASK_SIZE);
    }

    @Override
    public void run() {
        while (this.running) {
            try {
                LoopTask poll = tasks.poll(waiting, TimeUnit.SECONDS);
                poll.execute();
            } catch (Throwable e) {
            }
        }
    }

    public void start() {
        this.running = true;
        demaon.start();
    }

    public void stop() {
        this.running = false;
        demaon.interrupt();
    }

    public void put(T task) throws InterruptedException {
        tasks.put(task);
    }
}
